<template>
  <div >
    <div >
        <n-card title="AI图片生成" header>
        <div class="header">
            <div>
            <NButton type="primary" @click="onClickAdd">
                添加AI配置
            </NButton>
            </div>
            <div>
            <n-input-group>
                <n-input v-model:value="params.keyword" clearable placeholder="请输入插件关键词" :style="{ width: '100%' }" />
                <n-button @click="List" type="primary" ghost>
                    搜索
                </n-button>
                </n-input-group>
            </div>
        </div>
        </n-card>
        <div class="box">
        <!-- 数据表 -->
        <div class="table-box">
            <div >
            <n-data-table
                striped 
                 
                ref="table"
                :columns="columns"
                :data="data"
            />
            </div>
            <div class="pagination">
                <div>共{{pagination.total}}条数据</div>
                <div>
                <n-pagination
                v-model:page="params.pageNum"
                v-model:page-size="params.pageSize"
                :page-count="setPagination(pagination.total,params.pageSize )"
                show-size-picker
                :page-sizes="pageSizes"
                :on-update:page="pageNext"
                :on-update:page-size="sizeNext"
                />
                </div>
            </div>
        
        </div> 
            
        </div>
    </div>


  <yingModal :width="'800px'" :height="'600px'" :title="popTitle" @close="showModal=false" @confirm="submitCallback" :SkuShow="showModal" >
    <template #content>
        <n-form
          ref="formRef"
          :model="formValue"
          :rules="rules"
        >
        
        <n-form-item  label="ai商家" path="type">
            <n-select
            v-model:value="formValue.ai_type"
                :style="{ width: '400px' }" 
                filterable 
                placeholder="请选择类型"
                :options="typeOptions"
                clearable
            />
        </n-form-item>
          
          <n-form-item v-if="formValue.ai_type != '1'" label="APPID" path="ai_APPID">
            <n-input v-model:value="formValue.ai_APPID" placeholder="请输入标题" />
          </n-form-item>

          <n-form-item v-if="formValue.ai_type != '1'" label="APISecret" path="ai_APISecret">
            <n-input v-model:value="formValue.ai_APISecret" placeholder="请输入标题" />
          </n-form-item>

          <n-form-item v-if="formValue.ai_type != '1'" label="APIKEY" path="ai_APIKEY">
            <n-input v-model:value="formValue.ai_APIKEY" placeholder="请输入标题" />
          </n-form-item>

          <n-form-item v-if="formValue.ai_type != '1'" label="备注" path="ai_memo">
            <n-input v-model:value="formValue.ai_memo" placeholder="请输入标题" />
          </n-form-item>
          <n-form-item v-if="popTitle == '编辑'" label="状态">
            <n-switch v-model:value="formValue.status">
              <template #checked>
                启动
              </template>
              <template #unchecked>
                禁用
            </template>
            </n-switch>
          </n-form-item>
        </n-form>
    </template>
  </yingModal>
    <n-modal  v-model:show="uploadShow"
    :mask-closable="false"
    preset="dialog"
    style="width: 1000px;"
    :title="'文件管理'"
    content="你确认?"
    positive-text="确定"
    negative-text="关闭"      
    @positive-click="uploadShow=false"
    @negative-click="uploadShow=false"
    >
    <div class="box-upload">
        <Upload type="1" @selectImage="selectImageFun"/>
    </div>
</n-modal>
  </div>
</template>

<script setup lang="ts">
import { NAvatar, NButton, NImage, NSwitch, NTag  } from 'naive-ui'
import commonEditor from '@/components/common/commonEditor.vue'
import type { FormInst } from 'naive-ui'
import { nextTick, onMounted, ref } from 'vue'
import { Https,setPagination } from "@/utils"
import api from './api'
import Upload from "@/views/upload/index.vue"
import yingModal from '@/components/common/YingModal.vue'
const router = useRouter()
const route = useRoute()
const pluginInfo = ref({})
const messageStatus = ref(false)
const uploadShow = ref(false)
const typeOptions = ref([
  {
    label:'默认',
    value:'1'
  },
  {
    label:'讯飞',
    value:'2'
  },
  {
    label:'腾讯',
    value:'3'
  },
  {
    label:'华为',
    value:'4'
  }
])
const TextImage = ref('');
const token = ref('')
onMounted(() => {
     
    token.value = JSON.parse(localStorage.getItem("vue-naivue-admin_auth"))['token']
    List();
    // myPluin()
})
const typeImage = ref('')
const uploadImage = () =>{
  typeImage.value = "富文本"
  uploadShow.value = true;
}
const getEditorValue = (data) => {
 
   formValue.value.content = data
}

const selectImageFun =(selectImageList) =>{
  if(typeImage.value == '富文本'){

    TextImage.value = Https() + selectImageList[0];
    uploadShow.value = false;
    return
  }
  formValue.value.image = selectImageList[0];  // 只获取第一张图
  uploadShow.value = false
} 

 

const pageSizes = [
  {
    label: '10 每页',
    value: 10
  },
  {
    label: '20 每页',
    value: 20
  },
  {
    label: '30 每页',
    value: 30
  },
  {
    label: '40 每页',
    value: 40
  }
]


const pagination = ref({
  total:10
  
})
const formRef = ref<FormInst | null>(null);

const showModal = ref(false);
const popTitle:any = ref('添加公告');
const params = ref({
  pageNum: 1,
  pageSize: 10,
  keyword: '',
  user_id:''
})

const formValue = ref({
  ai_memo:"",
  ai_APIKEY:"",
  ai_APISecret:"",
  ai_APPID:"",
  ai_type:null,
  status:true
  
})

const rules = {
    ai_APPID: {
        required: true,
        message: '请输入ai_APPID',
        trigger: 'blur'
    },
    ai_APISecret: {
        required: true,
        message: '请输入ai_APISecret',
        trigger: 'blur'
    },
    ai_APIKEY: {
        required: true,
        message: '请输入ai_APIKEY',
        trigger: 'blur'
    },
    status: {
        required: true,
        message: '请选择状态',
        trigger: 'blur'
    },
    ai_memo: {
        required: false,
        message: '请输入备注',
        trigger: 'blur'
    } 
   
  
}

const columns = [
  {
    title: 'id',
    key: 'id',
    ellipsis: {
      tooltip: true
    }
 
  },
  {
    title: 'uuid',
    key: 'ai_uuid',
    ellipsis: {
      tooltip: true
    }
 
  },
  {
    title: 'appid',
    key: 'ai_APPID',
    // width: 200,
    ellipsis: {
      tooltip: true
    }
  },
  {
    title: 'APISecret',
    key: 'ai_APISecret',
    // width: 200,
    ellipsis: {
      tooltip: true
    },
  },
 
  {
    title: 'APIKEY',
    key: 'ai_APIKEY',
    // width: 200,
    ellipsis: {
      tooltip: true
    },
    
    
  },
  {
    title: '备注',
    key: 'ai_memo',
    // width: 200,
    ellipsis: {
      tooltip: true
    },
  },
  {
    title: '第三方api机构',
    key: 'ai_type',
    // width: 200,
    ellipsis: {
      tooltip: true
    },
    render: (item) => setType(item)
    
  },
  {
    title: '状态',
    key: 'status',
    ellipsis: {
      tooltip: true
    },
    render: (item) => setStatus(item)
  },
 
  {
    title: '操作',
    key: 'actions',
    width: 360,
    align: 'right',
    fixed: 'right',
    hideInExcel: true,
  
    render(row) {
      return [
      
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            style: 'margin-left: 12px;',
            secondary: true,
            onClick: () => handleOpenRolesSet(row),
          },
          {
            default: () => '编辑',
            icon: () => h('i', { class: 'i-fe:edit' }),
          },
        ),

        h(
          NButton,
          {
            size: 'small',
            type: 'error',
            style: 'margin-left: 12px;',
            onClick: () => handleDelete(row.id),
          },
          {
            default: () => '删除',
            icon: () => h('i', { class: 'i-material-symbols:delete-outline text-14' }),
          },
        ),
      ]
    },
  },

]

 
 
function setType(item){
    // console.log(item)
    if(item.ai_type == '1')
        return '官方'
    if(item.ai_type == '2')
        return '讯飞'
    if(item.ai_type == '3')
      return '腾讯'
    if(item.ai_type == '4')
      return '华为'
}
 

function setStatus(item){
    // console.log(item)
    if(item.status)
        return h('span', { style: { color: 'green' } },'启用')
    else
        return h('span', { style: { color: 'red' } },'禁用')
}
const data: any = ref([])

async function handleDelete(id){
  const res: any = await api.DeleteApi({
    id:id
  })
  if(res.code == 200){
    List();
    $message.success('删除成功!')
  }else{
    
  }

}
const messageParams: any = ref({
  show: false,
  status: '403',
  loading: true,
})

const handleOpenRolesSet =(item) =>{
 
    formValue.value = item;
    if(formValue.value.endTime == "None" || formValue.value.endTime == "" || formValue.value.endTime == Node || formValue.value.endTime == "NaT"){
      formValue.value.endTime = ""
      formValue.value.startTime = ""
    }else{
      formValue.value.endTime = new Date(formValue.value.endTime).getTime()
      formValue.value.startTime = new Date(formValue.value.startTime).getTime()
    }
    
    formValue.value.sort = String(formValue.value.sort) 
    popTitle.value = '编辑';
    showModal.value = true;
} 

async function List() {
  try {
    messageParams.value.loading = true
    const res: any = await api.ListApi(params.value)
    if (res.code == 200) {
      messageParams.value.loading = false
      pagination.value.total = res.data.total
      data.value = res.data.list
    }
    else {
      messageParams.value.show = false
      messageParams.value.status = '500'
    }
  }
  catch (error) {
    console.error(error)
  }
}
function onClickAdd(){
  popTitle.value = '添加AI配置'
  showModal.value = true
  formValue.value = {
    ai_memo:"",
    ai_APIKEY:"",
    ai_APISecret:"",
    ai_APPID:"",
    ai_type:null,
    status:true
  }
}
async function submitCallback() {
    messageParams.value.loading = true
    formRef.value?.validate((errors) => {
        if (!errors) {
        formValue.value.user_id = route.query.user_id
        formValue.value.plugin_id = route.query.plugin_id
        if(popTitle.value == '添加AI配置')
            AddFun();
        else
            EditFun();
        }
        else {
        showModal.value = true
        return 
    
        }
    })
}

async function AddFun(){
    
    const newData =  formValue.value
  
    const res: any = await api.AddApi(newData)
    if(res.code == 200){
        List();
        showModal.value = false;
        $message.success('添加成功!')
        
    }else{
        $message.error(res.message)
    }
}

async function EditFun(){
  const res: any = await api.EditApi(formValue.value)
  if(res.code == 200){
    List();
    $message.success('编辑成功!')
    showModal.value = false;
  }else{
    $message.error(res.message)
  }
}

function pageNext(page){
  params.value.pageNum = page
  List();
}
function sizeNext(size){
    params.value.pageNum = 1
    params.value.pageSize = size
    List();
}


function cancelCallback() {
  List();
  showModal.value = false
}

function goTo(path){
    router.push(path)
}

function toStore(item){
    router.push({
      path:'/plugin/goodsPlugin/index',
      query:{
        user_id:route.query.user_id,
        store_id:item.businessId,
      }
    })
    // router.push('/plugin/goodsPlugin/index')
}
</script>

<style scoped>
 .box {
    height: 75vh;
    overflow-y: auto;
}
.table-box{
  padding: 20px;
}
.box-modal{
  width: 800px;
  /* height: 350px; */
  background: white;
  /* overflow-y: auto; */
}
.pagination{
  display: flex;
  justify-content: right;
  /* height: 60px; */
  gap: 10px;
  align-items: center;
  position: relative;
  top: 20px;
}
.header{
  display: flex;gap: 10px;
}
.Message{
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 200px;
}
.imageUpload{
  width:100px;
  height:100px;
  border:1px solid #eee;
  display: flex;
  justify-content: center;
  border-radius: 6px;
  align-items: center;
}
.imageUpload:hover{
  border:1px solid rgb(49, 108, 114);
}
</style>
